package com.atguigu.gmall.task.listener;

import com.atguigu.gmall.task.config.DeadLetterConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @author: 李旭
 * @create: 2021-07-24 11:37
 * <p>
 * 消费方
 **/
@Component
public class ConsumerListener {


    //接收死信消息
    @RabbitListener(queues = DeadLetterConfig.queue_dead_2)
    public void receiverDeadLetterMessage(Channel channel, Message message, String msg) {
        System.out.println("接收到的消息是:" + msg + ":时间是:" + new Date());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //接收普通消息
    @RabbitListener(queues = "queue1")
    public void receiverMessage(Channel channel, Message message, String msg) {
        //System.out.println("接收到的消息是:" + new String(message.getBody()));
        System.out.println("接收到的消息是:" + msg);
        try {
            //处理
            int i = 1 / 0;
            //手动应答
            //参数1：消息的标记
            //参数2：是否批量应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //e.printStackTrace();
            //打印日志 或 给个机会

            if (!message.getMessageProperties().isRedelivered()) {
                //第一次投递了
                //参数1：消息的标记
                //参数2：是否批量应答
                //参数3：是否要放回队列中 如果放回去就重新投递  如果不放回去 表示此消息进行丢弃
                System.out.println("第一次投递了");
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                            false, true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } else {
                //第二次投递了
                System.out.println("第二次投递了");
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }


    }
}
